package com.example.demo.Service.lmp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.Dto.AddItemDTO;
import com.example.demo.Mapper.CartMapper;
import com.example.demo.Service.CartItemService;
import com.example.demo.Service.CartService;
import com.example.demo.VO.CartInfoVo;
import com.example.demo.po.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CartServiceImp extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CartItemService cartItemService;
    //根据用户id查询并添加有效购物车id
    @Override
    public Long addCart(Long userId) {
        List<Cart> id = list(new QueryWrapper<Cart>().eq("user_id", userId));
        if (id==null){
           Cart cart = new Cart().setUserId(userId).setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now()).setStatus(0);
           if (!(save(cart))){
               throw new RuntimeException("添加失败");
           }
           return cart.getId();
       }
        for (Cart cart : id){
            if (cart.getStatus()==0){
                return cart.getId();
            }
        }
        Cart cart = new Cart().setUserId(userId).setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now()).setStatus(0);
        if (!(save(cart))){
            throw new RuntimeException("添加失败");
        }
        return cart.getId();
    }
    @Override
    public CartInfoVo getcart(Long userId) {
        Object o = redisTemplate.opsForValue().get("cart:" + userId);
        if (o != null){
            return JSONUtil.toBean(o.toString(), CartInfoVo.class);
        }
        Cart userId1 = getOne(new QueryWrapper<Cart>().eq("user_id", userId));
        CartInfoVo cartInfoVo = BeanUtil.copyProperties(userId1, CartInfoVo.class);
        CartInfoVo cartItem = cartItemService.getCartItem(cartInfoVo);
        redisTemplate.opsForValue().set("cart:" + userId, JSONUtil.toJsonStr(cartItem));
        return cartItem;
    }
}
